__all__ = ["ranks"]

class RankManager(object):
    """
    This object is here to ensure that we host a container 
    """
    def __init__(self):
        """
        Default constructor, ensure that all object and variables are 
        initialised. Called automatically on object creation.
        """
        self.positions = []
        self.detailedInfo = {}
        self.refreshRanks()
        
    def refreshRanks(self):
        """
        This function should be called when we want the ranks in the database
        to be refreshed. This should reupdate the internal libraries and 
        containers so that it contains the updated information from the
        database. This should only be called at unimportant times as it has the
        potential to lag the server.
        """
        from wcs.libs.database import getDatabase
        
        database = getDatabase()
        database.execute("""SELECT level,userID,name FROM player ORDER BY level
                            DESC,name ASC""")
        level, dbUserid, name = database.cursor.fetchall()
        self.positions.append(dbUserid)
        self.detailedInfo[dbUserid] = {}
        self.detailedInfo[dbUserid]["name"]  = name
        self.detailedInfo[dbUserid]["level"] = level
    
    def getPlayerRank(self, dbUserid):
        """
        Returns a player's rank dependant on the player's position within the 
        database based on their overall level.
        
        @param int dbUserid The database ID of a particular userid
        """
        if dbUserid in self.positions:
            return self.positions.index(dbUserid) + 1
        return len(self.positions)
    
    def getRankPositions(self, lowerOrdinal, upperOrdinal=None):
        """
        Retrieves a container of player's based upon the rank ordinals passed.
        
        @param int lowerOrdinal The position of the lower based rank position
        @param optional int upperOrdinal The position to stop the retrieval
        @return list The player's in between ranks of lowerOrdinal and 
                     upperOrdinal. If no upperOrdinal, the individual player is
                     returned. i.e "1" into the lowerOrdinal and None into upper
                     will return rank 1 position.
        """
        lowerOrdinal -= 1
        if upperOrdinal is None:
            if lowerOrdinal < len(self.positions):
                return self.positions[lowerOrdinal] 
            return None
        else:
            upperOrdinal -= 1
        return self.positions[lowerOrdinal:upperOrdinal]
    
ranks = RankManager()